package com.lsj.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lsj.config.redis.RedisKey;
import com.lsj.core.exception.CustomerException;
import com.lsj.core.lock.DistributedLock;
import com.lsj.core.lock.LockKey;
import com.lsj.core.response.ResponseType;
import com.lsj.core.util.ExceptionHelperUtil;
import com.lsj.core.util.QueryHelperUtil;
import com.lsj.dto.sys.OrgDto;
import com.lsj.dto.sys.UserOrgDto;
import com.lsj.mapper.MySysOrgMapper;
import com.lsj.mapper.SysOrgMapper;
import com.lsj.mapper.SysUserMapper;
import com.lsj.mapper.SysUserOrgMapper;
import com.lsj.mapper.entity.SysOrg;
import com.lsj.mapper.entity.SysUser;
import com.lsj.mapper.entity.SysUserOrg;
import com.lsj.service.UserOrgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author:lin.sj
 * @Data:2021/7/14 20:33
 * @Desc:
 */
@Service
@Slf4j
public class UserOrgServiceImpl implements UserOrgService {
    @Autowired
    SysUserOrgMapper sysUserOrgMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysOrgMapper sysOrgMapper;
    @Autowired
    MySysOrgMapper mySysOrgMapper;

    /**
     * @Author: lin.sj
     * @Date: 2021/7/14 20:39
     * @Desc:
     * 1.更新用户与组织关系
     * 2.更新完毕后，需要从redis中去除用户加载的信息(因为权限变了),通过CacheEvict操作
     * 3.为保证插入时组织机构还存在，需要加上组织机构锁
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = RedisKey.USER_KEY,key = "#dto.account")
    @DistributedLock(LockKey.org_tree_key)
    public void updateOrgForUser(UserOrgDto dto) {
        //检查是否存在用户与机构
        SysUser sysUser = sysUserMapper.selectById(dto.getUserId());
        ExceptionHelperUtil.nullObjException(sysUser,"当前用户不存在，无法绑定！");
        SysOrg sysOrg = sysOrgMapper.selectById(dto.getOrgId());
        ExceptionHelperUtil.nullObjException(sysOrg,"当前组织机构不存在，无法绑定！");
        if(sysOrg.getId() == 0){
            throw new CustomerException(ResponseType.error,"不能绑定根节点组织！");
        }
        //删除与用户关联的组织机构
        LambdaQueryWrapper<SysUserOrg> w = QueryHelperUtil.getLambdaWrapper(SysUserOrg.class);
        w.eq(SysUserOrg::getUserId,dto.getUserId());
        sysUserOrgMapper.delete(w);
        //插入新的用户与组织机构的关系
        SysUserOrg sysUserOrg = new SysUserOrg();
        sysUserOrg.setUserId(dto.getUserId()).setOrgId(dto.getOrgId());
        sysUserOrgMapper.insert(sysUserOrg);
    }
    /**
     * @Author: lin.sj
     * @Date: 2021/8/18 20:36
     * @Desc: 根据用户查找关联的组织机构
     **/
    @Override
    public OrgDto findOrgByUserId(Long userId) {
        SysOrg sysOrg = mySysOrgMapper.findOrgByUserId(userId);
        return Convert.convert(OrgDto.class,sysOrg);
    }
}
